/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.logging.logback;

import ch.qos.logback.classic.pattern.MDCConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import io.iec.edp.caf.commons.utils.InvokeService;
import io.iec.edp.caf.commons.utils.StringUtils;
import io.iec.edp.caf.logging.ClassUtils;
import io.iec.edp.caf.logging.CommonConstant;
import io.iec.edp.caf.logging.TraceIdGenerator;
import org.slf4j.MDC;

/**
 * @author wangyandong
 * @date 2021/05/22 14:03
 *
 */
public class CafTraceIdPatternConverter extends MDCConverter {
    private static final String CONTEXT_CLASS_NAME="org.skywalking.apm.agent.core.context.ContextManager";
    private Class clazz;
    private boolean apmIsAvailable = false;

    public CafTraceIdPatternConverter(){

        this.apmIsAvailable = ClassUtils.isPresent(CONTEXT_CLASS_NAME,null);
        if(this.apmIsAvailable)
        clazz = InvokeService.getClass(CONTEXT_CLASS_NAME);
    }

    @Override
    public String convert(ILoggingEvent iLoggingEvent) {
        String traceId = null;
        //判断skywalking是否启用，类型是否加载
        if (apmIsAvailable) {
            //ContextManager.getGlobalTraceId();
            boolean isActive = (Boolean) InvokeService.invokeStaticGenericMethod(clazz, CONTEXT_CLASS_NAME, "isActive");
            if (isActive)
                traceId = (String) InvokeService.invokeStaticGenericMethod(clazz, CONTEXT_CLASS_NAME, "getGlobalTraceId");
        }

        if (StringUtils.isEmpty(traceId)) {
            traceId = MDC.get(CommonConstant.LOG_TRACE_ID);
            if (StringUtils.isEmpty(traceId)) {
                //生成一个管理起来
                traceId = TraceIdGenerator.generate();
                MDC.put(CommonConstant.LOG_TRACE_ID, traceId);
            }
        }
        return traceId;
    }
}
